package com.ilink.groundservice.controller.AiXNew;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ilink.groundservice.entity.VO.AiX.AiXLiteratureResponse;
import com.ilink.groundservice.service.Literature.AiXLiteratureService;
import com.ilink.ilinkapi.dto.ground.AiX.AiXLiteratureFilterRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXLiteratureInsertRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXLiteratureUpdateRequest;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.ilinkcommon.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Slf4j
@RequestMapping("/ground/aix/literature")
@RestController
@RequiredArgsConstructor
public class AiXLiteratureController {

    private final AiXLiteratureService literatureService;

    @MethodLog("获取文献列表")
    @GetMapping("/list")
    public R getLiteratureList(@RequestParam(required = false) Long areaId,
                               @RequestParam(required = false) String tag,
                               @RequestParam(required = false) String keyword,
                               @RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer size) {
        try {
            String userId = UserContext.getUserId();
            
            AiXLiteratureFilterRequest request = new AiXLiteratureFilterRequest();
            request.setAreaId(areaId);
            request.setTag(tag);
            request.setKeyword(keyword);
            request.setPage(page);
            request.setSize(size);
            
            IPage<AiXLiteratureResponse> responseIPage = literatureService.getLiteratureList(request, userId);
            log.info("获取文献列表成功, total: {}", responseIPage.getTotal());
            return R.ok("文献列表获取成功", responseIPage);
        } catch (Exception e) {
            log.error("获取文献列表失败: {}", e.getMessage());
            return R.error("获取文献列表失败: " + e.getMessage());
        }
    }

    @MethodLog("获取文献详情")
    @GetMapping("/{literatureId}")
    public R getLiteratureDetail(@PathVariable Long literatureId) {
        try {
            String userId = UserContext.getUserId();
            AiXLiteratureResponse response = literatureService.getLiteratureById(literatureId, userId);
            log.info("获取文献详情成功, literatureId: {}", literatureId);
            return R.ok("文献详情获取成功", response);
        } catch (Exception e) {
            log.error("获取文献详情失败: {}", e.getMessage());
            return R.error("获取文献详情失败: " + e.getMessage());
        }
    }

    @MethodLog("获取文献PDF下载链接")
    @GetMapping("/{literatureId}/download")
    public R getLiteraturePdfUrl(@PathVariable Long literatureId) {
        try {
            String userId = UserContext.getUserId();
            String pdfUrl = literatureService.getLiteraturePdfUrl(literatureId, userId);
            log.info("获取文献PDF下载链接成功, literatureId: {}", literatureId);
            return R.ok("文献PDF下载链接获取成功", pdfUrl);
        } catch (Exception e) {
            log.error("获取文献PDF下载链接失败: {}", e.getMessage());
            return R.error("获取文献PDF下载链接失败: " + e.getMessage());
        }
    }

    @MethodLog("收藏文献")
    @PostMapping("/{literatureId}/favorite")
    public R favoriteLiterature(@PathVariable Long literatureId) {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            literatureService.favoriteLiterature(literatureId, userId);
            log.info("收藏文献成功, literatureId: {}, userId: {}", literatureId, userId);
            return R.ok("文献收藏成功");
        } catch (Exception e) {
            log.error("收藏文献失败: {}", e.getMessage());
            return R.error("收藏文献失败: " + e.getMessage());
        }
    }

    @MethodLog("取消收藏文献")
    @DeleteMapping("/{literatureId}/favorite")
    public R unfavoriteLiterature(@PathVariable Long literatureId) {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            literatureService.unfavoriteLiterature(literatureId, userId);
            log.info("取消收藏文献成功, literatureId: {}, userId: {}", literatureId, userId);
            return R.ok("取消收藏成功");
        } catch (Exception e) {
            log.error("取消收藏文献失败: {}", e.getMessage());
            return R.error("取消收藏文献失败: " + e.getMessage());
        }
    }

    @MethodLog("获取收藏文献列表")
    @GetMapping("/favorites")
    public R getFavoriteLiteratures(@RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "10") Integer size) {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            IPage<AiXLiteratureResponse> responseIPage = literatureService.getFavoriteLiteratures(page, size, userId);
            log.info("获取收藏文献列表成功, userId: {}, total: {}", userId, responseIPage.getTotal());
            return R.ok("收藏文献列表获取成功", responseIPage);
        } catch (Exception e) {
            log.error("获取收藏文献列表失败: {}", e.getMessage());
            return R.error("获取收藏文献列表失败: " + e.getMessage());
        }
    }

    @MethodLog("获取文献标签")
    @GetMapping("/categories/tags")
    public R getAllLiteratureTags(@RequestParam Long areaId) {
        try {
            List<String> tags = literatureService.getAllLiteratureTags(areaId);
            log.info("获取文献标签成功, count: {}", tags.size());
            return R.ok("文献标签获取成功", tags);
        } catch (Exception e) {
            log.error("获取文献标签失败: {}", e.getMessage());
            return R.error("获取文献标签失败: " + e.getMessage());
        }
    }

    @MethodLog("搜索文献")
    @GetMapping("/search")
    public R searchLiterature(@RequestParam String query,
                              @RequestParam(required = false) String searchType,
                              @RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "10") Integer size) {
        try {
            String userId = UserContext.getUserId();
            
            IPage<AiXLiteratureResponse> responseIPage = literatureService.searchLiteratures(query, searchType, page, size, userId);
            log.info("搜索文献成功, query: {}, total: {}", query, responseIPage.getTotal());
            return R.ok("文献搜索成功", responseIPage);
        } catch (Exception e) {
            log.error("搜索文献失败: {}", e.getMessage());
            return R.error("搜索文献失败: " + e.getMessage());
        }
    }

    @MethodLog("获取推荐文献")
    @GetMapping("/recommendations")
    public R getRecommendedLiteratures(@RequestParam(defaultValue = "10") Integer limit) {
        try {
            String userId = UserContext.getUserId();
            List<AiXLiteratureResponse> literatures = literatureService.getRecommendedLiteratures(limit, userId);
            log.info("获取推荐文献成功, count: {}", literatures.size());
            return R.ok("推荐文献获取成功", literatures);
        } catch (Exception e) {
            log.error("获取推荐文献失败: {}", e.getMessage());
            return R.error("获取推荐文献失败: " + e.getMessage());
        }
    }

    @MethodLog("上传文献")
    @PostMapping("/upload")
    public R uploadLiterature(AiXLiteratureInsertRequest request) {
        try {
            Long literatureId = literatureService.insertLiterature(request);
            log.info("上传文献成功, literatureId: {}, title: {}", literatureId, request.getTitle());
            return R.ok("文献上传成功", literatureId);
        } catch (Exception e) {
            log.error("上传文献失败: {}", e.getMessage());
            return R.error("上传文献失败: " + e.getMessage());
        }
    }

    @MethodLog("获取热门文献")
    @GetMapping("/popular")
    public R getPopularLiteratures(@RequestParam(defaultValue = "10") Integer limit) {
        try {
            String userId = UserContext.getUserId();
            List<AiXLiteratureResponse> literatures = literatureService.getPopularLiteratures(limit, userId);
            log.info("获取热门文献成功, count: {}", literatures.size());
            return R.ok("热门文献获取成功", literatures);
        } catch (Exception e) {
            log.error("获取热门文献失败: {}", e.getMessage());
            return R.error("获取热门文献失败: " + e.getMessage());
        }
    }

    // 管理员接口：创建文献
    @MethodLog("创建文献")
    @PostMapping("/create")
    public R createLiterature(@RequestBody AiXLiteratureInsertRequest request) {
        try {
            Long literatureId = literatureService.insertLiterature(request);
            log.info("创建文献成功, literatureId: {}", literatureId);
            return R.ok("文献创建成功", literatureId);
        } catch (Exception e) {
            log.error("创建文献失败: {}", e.getMessage());
            return R.error("创建文献失败: " + e.getMessage());
        }
    }

    // 管理员接口：更新文献
    @MethodLog("更新文献")
    @PostMapping("/update")
    public R updateLiterature(@RequestBody AiXLiteratureUpdateRequest request) {
        try {
            literatureService.updateLiterature(request);
            log.info("更新文献成功, literatureId: {}", request.getLiteratureId());
            return R.ok("文献更新成功");
        } catch (Exception e) {
            log.error("更新文献失败: {}", e.getMessage());
            return R.error("更新文献失败: " + e.getMessage());
        }
    }

    // 管理员接口：删除文献
    @MethodLog("删除文献")
    @PostMapping("/delete/{literatureId}")
    public R deleteLiterature(@PathVariable Long literatureId) {
        try {
            literatureService.deleteLiterature(literatureId);
            log.info("删除文献成功, literatureId: {}", literatureId);
            return R.ok("文献删除成功");
        } catch (Exception e) {
            log.error("删除文献失败: {}", e.getMessage());
            return R.error("删除文献失败: " + e.getMessage());
        }
    }
    
    // 管理员接口：更新文献封面
    @MethodLog("更新文献封面")
    @PostMapping("/{literatureId}/cover")
    public R updateLiteratureCover(@PathVariable Long literatureId,
                                  @RequestParam("coverFile") MultipartFile coverFile) {
        try {
            literatureService.updateLiteratureCover(literatureId, coverFile);
            log.info("更新文献封面成功, literatureId: {}", literatureId);
            return R.ok("文献封面更新成功");
        } catch (Exception e) {
            log.error("更新文献封面失败: {}", e.getMessage());
            return R.error("更新文献封面失败: " + e.getMessage());
        }
    }

    @MethodLog("获取文献最常用的8个标签")
    @GetMapping("/get_literature_tags")
    public R getLiteratureTags(@RequestParam Long areaId) {
        try {
            List<String> tags = literatureService.getLiteratureTags(areaId);
            return R.ok("文献最常用的8个标签", tags);

        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }
} 